package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.enums.*;
import cn.huiyunche.base.service.form.VehiClesInfoFrom;
import cn.huiyunche.base.service.interfaces.*;
import cn.huiyunche.base.service.mappers.*;
import cn.huiyunche.base.service.mappers.ext.SServiceOrderViewMapper;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.base.service.vo.*;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务订单接口实现类
 *
 * @author Administrator
 */
@Service
class SServiceOrderServiceImpl implements SServiceOrderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SServiceOrderServiceImpl.class);

    @Autowired
    private SServiceOrderMapper sServiceOrderMapper = null;

    @Autowired
    private SServiceOrderViewMapper sServiceOrderViewMapper = null;

    @Autowired
    private CWaybillService cWaybillService = null;

    @Autowired
    private CWaybillDetailMapper cWaybillDetailMapper = null;

    @Autowired
    private ServiceOrderStatusLogService serviceOrderStatusLogService = null;

    @Autowired
    private SServiceOrderTrailMapper sServiceOrderTrailMapper = null;

    @Autowired
    private SOrderMapper sOrderMapper = null;

    @Autowired
    private CWaybillAddressMapper cWaybillAddressMapper;

    @Autowired
    private SOrderProductService sOrderProductService;

    @Autowired
    private FeesService feesService;

    @Autowired
    private SServiceOrderFeedetailService sServiceOrderFeedetailService;

    @Autowired
    private SOrderStowageService sOrderStowageService;

    @Autowired
    private BStowageVehicleService bStowageVehicleService;

    @Autowired
    private CAccntTurnOverService cAccntTurnOverService = null;

    @Autowired
    private UserService userService = null;

    @Autowired
    private SServiceOrderVehicleService sServiceOrderVehicleService;

    @Autowired
    private SServiceOrderStatusLogService sServiceOrderStatusLogService;

    @Autowired
    private SServiceOrderTrailService sServiceOrderTrailService;

    @Autowired
    private BCompanyUserService bCompanyUserService = null;

    @Autowired
    private CompanyService companyService = null;

    @Autowired
    private SOrderPayRoleService sOrderPayRoleService = null;

    private SOrderPayRoleService getSOrderPayRoleService() {
        return this.sOrderPayRoleService;
    }

    private CompanyService getCompanyService() {
        return this.companyService;
    }

    private BCompanyUserService getBCompanyUserService() {
        return this.bCompanyUserService;
    }

    private UserService getUserService() {
        return this.userService;
    }

    private CAccntTurnOverService getCAccntTurnOverService() {
        return this.cAccntTurnOverService;
    }

    private SOrderMapper getSOrderMapper() {
        return this.sOrderMapper;
    }

    private SServiceOrderTrailMapper getSServiceOrderTrailMapper() {
        return this.sServiceOrderTrailMapper;
    }

    private CWaybillDetailMapper getCWaybillDetailMapper() {
        return this.cWaybillDetailMapper;
    }

    private ServiceOrderStatusLogService getServiceOrderStatusLogService() {
        return this.serviceOrderStatusLogService;
    }

    private CWaybillService getCWaybillService() {
        return this.cWaybillService;
    }

    private SServiceOrderViewMapper getSServiceOrderViewMapper() {
        return this.sServiceOrderViewMapper;
    }

    private SServiceOrderMapper getSServiceOrderMapper() {
        return this.sServiceOrderMapper;
    }

    @Override
    public long add(SServiceOrder order) {
        LOGGER.info("add param : {}", order);
        if (null == order) {
            LOGGER.error("add order must not be null");
            throw new IllegalArgumentException("客户订单数据不能为空！");
        }
        sServiceOrderMapper.insertSelective(order);
        return order.getId();
    }

    @Override
    public void update(SServiceOrder sOrder) {
        LOGGER.info("update param : {}", sOrder);
        if (null == sOrder) {
            LOGGER.error("update sOrder must not be null");
            throw new IllegalArgumentException("服务订单数据不能为空！");
        }
        sServiceOrderMapper.updateByPrimaryKeySelective(sOrder);
    }

    @Override
    public SServiceOrderAdminVo getSServiceOrderAdminVoById(Long id) {
        return this.getSServiceOrderViewMapper().selectOneByConditions(id);
    }

    @Override
    public void cancel(long customerOrderId) throws Exception {
        LOGGER.info("cancel param : {}", customerOrderId);
        if (0 == customerOrderId) {
            LOGGER.error("cancel customerOrderId must not be 0");
            throw new IllegalArgumentException("客户订单id不能是0！");
        }

        SServiceOrderExample example = new SServiceOrderExample();
        example.createCriteria().andCustomerOrderIdEqualTo(customerOrderId)
                .andStatusEqualTo(SServiceOrderStatusEnum.WAIT_DISPATCH.getValue());
        List<SServiceOrder> list = sServiceOrderMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(list)) {

            //当前用户
            UserVo userVo = userService.getCurrentUserVo();

            for (int i = 0; i < list.size(); i++) {
                SServiceOrder order = list.get(i);
                order.setStatus(SServiceOrderStatusEnum.CANCELED.getValue());
                sServiceOrderMapper.updateByPrimaryKeySelective(order);

                //保存服务订单状态变更
                SServiceOrderStatusLog statusLog = new SServiceOrderStatusLog();
                statusLog.setServiceOrderId(order.getId());
                statusLog.setStatus(SServiceOrderStatusEnum.CANCELED.getValue());
                statusLog.setUserId(userVo.getId());
                statusLog.setUserName(userVo.getUsername());
                sServiceOrderStatusLogService.addLog(statusLog);
            }
        }
    }

    /**
     * 查询服务订单列表
     *
     * @param page
     * @param sServiceOrderVo
     * @return
     */
    @Override
    public Map<String, Object> list(PageVo page, SServiceOrderAdminVo sServiceOrderVo) {
        LOGGER.info("list select service order params : {}.", JSON.toJSONString(sServiceOrderVo));
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            LOGGER.info("list select service order mapper.");
            page.setTotalRecord(this.getSServiceOrderViewMapper().count(sServiceOrderVo));

            List<SServiceOrderAdminVo> list = this.getSServiceOrderViewMapper().selectByConditions(page,
                    sServiceOrderVo);

            map.put("page", page);
            map.put("sorders", list);
        } catch (Exception e) {
            LOGGER.error("list select service order error : {}.", e);
            throw new BusinessException("查询服务订单列表异常");
        }
        return map;
    }

    /**
     * 服务订单确认交车
     *
     * @param ids    服务订单ID
     * @param status 服务订单状态
     * @return
     * @throws Exception
     */
    @Override
    public int updateServiceStatus(String ids, String status) throws Exception {
        LOGGER.info("updateServiceStatus update service order status params : id: {}, status: {}", ids, status);
        if (StringUtils.isBlank(ids)) {
            LOGGER.error("updateServiceStatus ids is not null");
            throw new Exception("服务订单ID不能为空");
        } else if (StringUtils.isBlank(status)) {
            LOGGER.error("updateServiceStatus status is not null");
            throw new Exception("服务订单状态不能为空");
        } else if (StringUtils.isBlank(SServiceOrderStatusEnum.getByValue(Integer.valueOf(status)).getText())) {
            LOGGER.error("updateServiceStatus Service order status is not legal");
            throw new Exception("服务订单状态不合法");
        }
        String[] id = ids.split(",");
        List<Long> serviceOrderIdList = new ArrayList<Long>();
        for (String string : id) {
            // 判断运单是否完成
            List<CWaybillByIdVo> cWaybills = this.getCWaybillService().selectBySid(Long.valueOf(string));
            if (CollectionUtils.isEmpty(cWaybills)) {
                LOGGER.info("updateServiceStatus Waybill record is empty");
                throw new Exception("此服务订单没有进行调度");
            }
            for (int i = 0; i < cWaybills.size(); i++) {
                if (cWaybills.get(i).getStatus() != WaybillStatusEnum.DONE.getValue()) {
                    LOGGER.info("updateServiceStatus This service order to save the waybill in the unfinished state");
                    throw new Exception("此服务订单“" + cWaybills.get(i).getWaybillCode() + "”存所在的运单处于未完成状态");
                }
            }

            SServiceOrder sServiceOrder = this.getSServiceOrderMapper().selectByPrimaryKey(Long.valueOf(string));

            // 判断服务订单状态是否为：“已发车”
            if (SServiceOrderStatusEnum.HAVE_ISSUSD.getValue() == sServiceOrder.getStatus()) {
                // 更新服务订单状态为：“已交车”
                sServiceOrder.setStatus(SServiceOrderStatusEnum.HAVE_DELIVERY.getValue());
                this.getSServiceOrderMapper().updateByPrimaryKeySelective(sServiceOrder);
            }
//			SServiceOrder serviceOrder = new SServiceOrder();
//			serviceOrder.setId(Long.valueOf(string));
//			serviceOrder.setStatus(Integer.valueOf(status));
//			// 更新服务订单状态
//			int res = sServiceOrderMapper.updateByPrimaryKeySelective(serviceOrder);
//			logger.info("updateServiceStatus Update record number ：{}", res);
            // 写日志信息
            SServiceOrderStatusLog log = new SServiceOrderStatusLog();
            log.setServiceOrderId(Long.valueOf(string));
            log.setStatus(SServiceOrderStatusEnum.getByValue(Integer.valueOf(status)).getValue());
            log.setUserId(0L);
            log.setUserName("system");
            log.setCreateTime(new Date());
            this.getServiceOrderStatusLogService().add(log);
            // 回写运单最后一次调度
            CWaybillDetailExample example = new CWaybillDetailExample();
            example.setOrderByClause("service_dispatch_times desc");
            example.createCriteria().andServiceOrderIdEqualTo(Long.valueOf(string));
            List<CWaybillDetail> wayBills = this.getCWaybillDetailMapper().selectByExample(example);
            if (CollectionUtils.isNotEmpty(wayBills)) {
                CWaybillDetail waybillDetail = wayBills.get(0);
                waybillDetail.setIsLastTime(true);
                this.getCWaybillDetailMapper().updateByPrimaryKeySelective(waybillDetail);
                LOGGER.info("waybillDetail: {}", JSONObject.toJSONString(waybillDetail));
                //更新写服务订单物流日志  已交车
                SServiceOrderTrail trail = new SServiceOrderTrail();
                trail.setInfo(SServiceOrderStatusEnum.HAVE_DELIVERY.getText());
                trail.setServiceOrderId(waybillDetail.getServiceOrderId());
                trail.setStatus(SServiceOrderStatusEnum.HAVE_DELIVERY.getValue());
                trail.setType(SServiceOrderTrailTypeEnum.SERVICE_ORDER_STATUS.getValue());
                // 写入服务订单物流信息
                this.getSServiceOrderTrailMapper().insertSelective(trail);
                LOGGER.info("insert serviceOrderTrail : {}", JSONObject.toJSONString(trail));
                // 更新当前位置
                CWaybillAddressExample addressExample = new CWaybillAddressExample();
                addressExample.createCriteria().andWaybillIdEqualTo(waybillDetail.getWaybillId());
                List<CWaybillAddress> address = this.cWaybillAddressMapper.selectByExample(addressExample);
                if (CollectionUtils.isNotEmpty(address)) {
                    CWaybillAddress add = address.get(0);
                    SServiceOrderTrail trails = new SServiceOrderTrail();
                    trails.setInfo(add.getReceiptProvinceName() + add.getReceiptCityName() + add.getReceiptCountyName() + add.getReceiptAddr());
                    trails.setServiceOrderId(waybillDetail.getServiceOrderId());
                    trails.setStatus(0);
                    trails.setType(SServiceOrderTrailTypeEnum.SERVICE_ORDER_ADDR.getValue());
                    // 写入服务订单物流信息
                    this.getSServiceOrderTrailMapper().insertSelective(trails);
                }
            }

            // 判断客户订单下所有服务订单是否已完成，如果已完成修改客户订单状态为已交车
            // 查询客户订单
            SServiceOrder sOrder = this.getSServiceOrderMapper().selectByPrimaryKey(Long.valueOf(string));
            SServiceOrderExample serviceOrderExample = new SServiceOrderExample();
            serviceOrderExample.createCriteria().andCustomerOrderIdEqualTo(sOrder.getCustomerOrderId()).andStatusNotEqualTo(SServiceOrderStatusEnum.HAVE_DELIVERY.getValue());
            List<SServiceOrder> serviceOrders = this.getSServiceOrderMapper().selectByExample(serviceOrderExample);
            if (CollectionUtils.isEmpty(serviceOrders)) {
                SOrder order = this.getSOrderMapper().selectByPrimaryKey(sOrder.getCustomerOrderId());
                // 判断客户订单状态是否为执行中
                if (COrderStatusEnum.IN_TRANSIT.getValue() == order.getStatus()) {
                    order.setStatus(COrderStatusEnum.COMPLETED.getValue());
                    // 修改客户订单状态为已交车
                    this.getSOrderMapper().updateByPrimaryKeySelective(order);

                    // 托运企业 客户订单 添加流水明细
                    if (order.getOrderType() == UserTypeEnum.SCOMPANY.getValue()) {
                        this.addTurnover(order);
                    }
                }
            }
            LOGGER.info("updateServiceStatus serviceOrderStatusLog new id: {}", log.getId());

            // 添加 交车短信通知
            serviceOrderIdList.add(Long.valueOf(string));

        }
        this.getCWaybillService().sendDeliveryMessage(serviceOrderIdList);
        return 0;
    }

    // 托运企业 客户订单 添加流水明细
    private void addTurnover(SOrder order) {
        LOGGER.info("customer order add turnover params order : {}.", JSON.toJSONString(order));
        try {
            List<CTurnover> list = new ArrayList<>();
            CTurnover cTurnover = new CTurnover();

            Long userId = order.getUserId();
            SOrderPayrole payRole = this.getSOrderPayRoleService().getUserByOrderId(order.getId());
            if (null != payRole) {
                userId = payRole.getUserId();
            }
            SUser user = this.getUserService().selectByPrimaryKey(userId);

            cTurnover.setPayType(AccPaytypeEnum.ORDER.getValue());
            cTurnover.setStatus(AccTurnoverStatusEnum.WAIT.getValue());
            cTurnover.setUserId(user.getId());
            cTurnover.setUserName(user.getRealName());
            cTurnover.setUserType(user.getUserType());
            cTurnover.setOrderId(order.getId());
            cTurnover.setOrderFee(order.getActualCost().abs().negate());
            cTurnover.setOrderActPay(order.getActualCost().abs().negate());
            cTurnover.setCreateTime(new Date());
            cTurnover.setUpdateTime(new Date());

            // 账单流水业务类型
            Boolean isVeneer = order.getIsVeneer();
            int bussinessType = 20;
            if (isVeneer != null && isVeneer) {
                bussinessType = AccBillTypeEnum.INCITY.getValue();
            } else {
                bussinessType = AccBillTypeEnum.INTERCITY.getValue();
            }
            cTurnover.setBussinessType(bussinessType);

            // 账单流水添加公司信息
            Long companyId = this.getBCompanyUserService().getCompanyIdByUserId(user.getId());
            if (null != companyId) {
                cTurnover.setCompanyId(companyId);
                Map<String, Object> companyNameMap = this.getCompanyService().selectById(companyId);
                BCompany bCompany = (BCompany) companyNameMap.get("companyData");
                if (null != bCompany) {
                    cTurnover.setCompanyName(bCompany.getCompanyName());
                }
            }

            list.add(cTurnover);
            this.getCAccntTurnOverService().addDetailsAndLedger(list, 0);
        } catch (Exception e) {
            LOGGER.error("customer order add turnover error : {}.", e);
            throw new BusinessException("客户订单已交车");
        }
    }

    /**
     * 根据主键ID 查询服务订单
     *
     * @param sorderId
     * @return
     */
    @Override
    public SServiceOrder selectById(Long sorderId) {
        try {
            LOGGER.info("selectById select serviceorder by id params sorderId : {}.", sorderId);
            return sServiceOrderMapper.selectByPrimaryKey(sorderId);
        } catch (Exception e) {
            LOGGER.error("selectById select serviceorder by id error : {}.", e);
            throw new BusinessException("根据主键查询服务订单异常");
        }
    }

    /**
     * 查询 服务订单
     *
     * @param example
     * @return
     */
    @Override
    public List<SServiceOrder> selectByExample(SServiceOrderExample example) {
        try {
            LOGGER.info("selectByExample select serviceorder by example : {}.", example);
            return sServiceOrderMapper.selectByExample(example);
        } catch (Exception e) {
            LOGGER.error("selectByExample select serviceorder by example error : {}.", e);
            throw new BusinessException("根据条件查询服务订单异常");
        }
    }

    /**
     * 服务订单调度次数 ＋1 -- 没用
     *
     * @param id
     * @return
     */
    @Override
    public int addDispatchTimes(Long id) {
        LOGGER.info("addDispatchTimes update sservice order dispatchTimes params id : {},", id);
        try {
            LOGGER.info("addDispatchTimes update sservice order dispatchTimes params id : {},", id);
            SServiceOrder sServiceOrder = this.getSServiceOrderMapper().selectByPrimaryKey(id);
            sServiceOrder.setDispatchTimes(sServiceOrder.getDispatchTimes() + 1);
            return this.getSServiceOrderMapper().updateByPrimaryKey(sServiceOrder);
        } catch (Exception e) {
            LOGGER.error("addDispatchTimes update sservice order dispatchTimes id:{}, error :{}.", id, e);
            throw new BusinessException("更新服务订单调度次数异常");
        }
    }

    @Override
    public List<SServiceOrderVo> getListByCOrderId(long customerOrderId, List<Integer> status) {
        LOGGER.info("getListByCOrderId params : {}, {}", customerOrderId, status);
        if (0 == customerOrderId) {
            LOGGER.error("getListByCOrderId customerOrderId must not be 0");
            throw new IllegalArgumentException("客户订单id不能是0！");
        }

        List<SServiceOrderVo> list = sServiceOrderViewMapper.selectByCOrderId(customerOrderId, status);
        if (CollectionUtils.isNotEmpty(list)) {
            return list;
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public BigDecimal computeFees(SOrder sOrder, SServiceOrder sServiceOrder, SServiceOrderVehicle vehicle, Boolean isPick, Boolean isDeliv, Boolean hasInvoice) {

        //查询物流产品id
        Long productId = sOrderProductService.getProductIdByCustemerOrderId(sOrder.getId());

        //构建车辆信息
        VehiClesInfoFrom vehicleInfo = new VehiClesInfoFrom();
        vehicleInfo.setAmount(1);
        vehicleInfo.setType(vehicle.getSysVehicleClass());
        vehicleInfo.setTypeId(vehicle.getSysVehicleClassid());
        List<VehiClesInfoFrom> vehicles = Arrays.asList(vehicleInfo);

        //查询客户订单是否匹配配置模型，则服务订单运输费也需要打折
        SOrderStowage sOrderStowage = sOrderStowageService.getByCustomerOrderId(sOrder.getId());
        BStowageModel stowageModel = null;
        if (null != sOrderStowage) {

            //查询客户订单的配置模型
            stowageModel = bStowageVehicleService.getById(sOrderStowage.getStowageModelId());

            //查询运单的配置模型
            BStowageModel model = bStowageVehicleService.getAvailable(BStowageModelEnum.WAYBILL);

            //折扣==原价/0.9*0.85==原价*(0.85/0.9)
            stowageModel.setDiscount(model.getDiscount().divide(stowageModel.getDiscount(), 4, RoundingMode.UP));
        }

        //计算费用
        Map<String, Object> map = feesService.queryFees(sOrder.getDepartCountyCode(), sOrder.getReceiptCountyCode(), sOrder.getDistance(), stowageModel, productId, sOrder.getDeliveryDate(), Integer.valueOf(Objects.equals(sOrder.getDeliveryTime(), null) ? "12" : sOrder.getDeliveryTime()), vehicles, sServiceOrder.getEstValue(), true, sOrder.getIsPick(), sOrder.getIsDeliv(), true, true);

        List<SOrderFeeDetailVo> fees = (List<SOrderFeeDetailVo>) map.get("fees");
        SOrderFeeDetailVo shippingFee = fees.stream().filter(fee -> BFeeTypeEnum.SHIPPING.getValue() == fee.getFeeCode()).collect(Collectors.toList()).get(0);
        SOrderFeeDetailVo invoiceFee = fees.stream().filter(fee -> BFeeTypeEnum.INVOICE_TAX.getValue() == fee.getFeeCode()).collect(Collectors.toList()).get(0);
        shippingFee.setCost(shippingFee.getCost().subtract(invoiceFee.getCost()));
        shippingFee.setActualAmount(shippingFee.getActualAmount().subtract(invoiceFee.getActualAmount()));

        //保存服务订单费用详情
        fees.stream().forEach(fee -> sServiceOrderFeedetailService.addFeeDetail(sServiceOrder.getId(), fee.getId(), fee.getFeeName(), fee.getCost(), fee.getActualAmount()));
        return (BigDecimal) map.get("actualtotal");
    }

    @Override
    public boolean assertStatus(Long customerOrderId, Integer status) {
        LOGGER.info("assertStatus params : {}, {}", customerOrderId, status);
        if (null == customerOrderId) {
            LOGGER.error("assertStatus  must not be null");
            throw new IllegalArgumentException("客户订单主键不能为空");
        }
        if (null == status) {
            LOGGER.error("assertStatus status must not be null");
            throw new IllegalArgumentException("状态不能为空");
        }

        List<SServiceOrderVo> list = this.getListByCOrderId(customerOrderId, null);
        if (CollectionUtils.isNotEmpty(list)) {
            long count = list.stream().filter(vo -> status != vo.getStatus()).count();
            if (0 == count) {
                return true;
            }
        }

        return false;
    }

    @Override
    public void updateStatusByCOrder(Long customerOrderId, Integer status) throws Exception {
        LOGGER.info("assertStatus params : {}, {}", customerOrderId, status);
        if (null == customerOrderId) {
            LOGGER.error("assertStatus  must not be null");
            throw new IllegalArgumentException("客户订单主键不能为空");
        }
        if (null == status) {
            LOGGER.error("assertStatus status must not be null");
            throw new IllegalArgumentException("状态不能为空");
        }

        UserVo userVo = userService.getCurrentUserVo();

        List<SServiceOrderVo> list = this.getListByCOrderId(customerOrderId, null);
        for (int i = 0; i < list.size(); i++) {
            SServiceOrderVo vo = list.get(i);
            SServiceOrder order = new SServiceOrder();
            order.setId(vo.getId());
            order.setStatus(status);
            sServiceOrderMapper.updateByPrimaryKeySelective(order);

            SServiceOrderStatusLog log = new SServiceOrderStatusLog();
            log.setServiceOrderId(vo.getId());
            log.setStatus(status);
            log.setUserId(userVo.getId());
            log.setUserName(userVo.getUsername());
            //保存状态变更记录
            serviceOrderStatusLogService.add(log);
            // 保存服务订单 物流信息
            this.addServiceTrailInfo(vo);
        }
    }

    // 保存服务订单 物流信息
    public int addServiceTrailInfo(SServiceOrderVo vo) {
        //更新写服务订单物流日志  DONE(90, "已完成"),
        SServiceOrderTrail trail = new SServiceOrderTrail();
        trail.setInfo(SServiceOrderStatusEnum.DONE.getText());
        trail.setServiceOrderId(vo.getId());
        trail.setStatus(SServiceOrderStatusEnum.DONE.getValue());
        trail.setType(SServiceOrderTrailTypeEnum.SERVICE_ORDER_STATUS.getValue());
        trail.setCreateTime(new Date());
        // 写入服务订单物流信息
        LOGGER.info("insert serviceOrderTrail : {}", JSONObject.toJSONString(trail));
        return this.getSServiceOrderTrailMapper().insertSelective(trail);
    }

    /**
     * @param customerOrderId 客户订单主键
     * @Title: serviceOrderIsNotDispatch
     * @Description: 判断客户订单下 所有的服务订单是否被调度过 －在客户订单取消的时候用
     * @return: bolean
     */
    @Override
    public boolean serviceOrderIsNotDispatch(Long customerOrderId) {
        LOGGER.info("serviceOrderIsNotDispatch params customerOrderId : {}.", customerOrderId);
        SServiceOrderExample example = new SServiceOrderExample();
        example.createCriteria().andCustomerOrderIdEqualTo(customerOrderId).andDispatchTimesGreaterThan(0);
        List<SServiceOrder> list = this.getSServiceOrderMapper().selectByExample(example);
        if (Collections.isNullOrEmpty(list)) {
            LOGGER.info("serviceOrderIsNotDispatch params customerOrderId : {}, true.", customerOrderId);
            return true;
        }
        throw new BusinessException("客户订单已被调度,不能取消。如有问题，请联系客服。");
    }

    @Override
    public int delete(Long customerOrderId) {
        LOGGER.info("delete param : {}", customerOrderId);
        if (null == customerOrderId) {
            LOGGER.info("delete param customerOrderId must not be null");
            throw new IllegalArgumentException("客户订单id不能为空");
        }

        //查询服务订单
        SServiceOrderExample example = new SServiceOrderExample();
        example.createCriteria().andCustomerOrderIdEqualTo(customerOrderId);
        List<SServiceOrder> sServiceOrders = sServiceOrderMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(sServiceOrders)) {
            LOGGER.info("delete sServiceOrders is empty");
            return 0;
        }

        //删除服务订单
        int count = sServiceOrderMapper.deleteByExample(example);

        sServiceOrders.forEach(serviceOrder -> {

            //删除服务订单车辆信息
            sServiceOrderVehicleService.delete(serviceOrder.getId());

            //删除服务订单费用详情
            sServiceOrderFeedetailService.delete(serviceOrder.getId());

            //删除服务订单状态变更记录
            sServiceOrderStatusLogService.delete(serviceOrder.getId());

            //删除服务订单物流信息
            sServiceOrderTrailService.delete(serviceOrder.getId());

        });

        return count;
    }

    @Override
    public int selectAfterByParams(Date date) throws Exception {
        LOGGER.info("selectAfterByParams params: {}", date);
        if (date == null || "".equals(date)) {
            LOGGER.info("params is not null");
            throw new BusinessException("查询时间条件不能为空");
        }
        SServiceOrderExample example = new SServiceOrderExample();
        example.createCriteria().andCreateTimeGreaterThan(date).andIsVeneerEqualTo(false);
        List<SServiceOrder> orders = this.getSServiceOrderMapper().selectByExample(example);
        if (CollectionUtils.isEmpty(orders)) {
            return 0;
        }
        return orders.size();
    }
}
